package com.weimei.conversionTreasure.viewModel;

import static com.mob.tools.utils.DH.SyncMtd.getPackageName;

import android.annotation.TargetApi;
import android.app.Application;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableField;
import androidx.databinding.ObservableInt;
import androidx.databinding.ObservableList;

import com.weimei.conversionTreasure.R;
import com.weimei.conversionTreasure.activity.AddPfActivity;
import com.weimei.conversionTreasure.activity.AddRecordActivity;
import com.weimei.conversionTreasure.activity.DetailRecordActivity;
import com.weimei.conversionTreasure.activity.KhRecordActivity;
import com.weimei.conversionTreasure.activity.LoginActivity;
import com.weimei.conversionTreasure.activity.PfRecordActivity;
import com.weimei.conversionTreasure.activity.SaveXlActivity;
import com.weimei.conversionTreasure.http.Repository;
import com.weimei.conversionTreasure.http.entity.FaJiaoListBean;
import com.weimei.conversionTreasure.http.entity.FormulaBean;
import com.weimei.conversionTreasure.http.entity.PaoLiangListBean;
import com.weimei.conversionTreasure.http.entity.TabOneEntity;
import com.weimei.conversionTreasure.utils.UserUtils;
import com.weimei.conversionTreasure.utils.ValidateUtils;
import com.weimei.conversionTreasure.weight.richEditText.utils.RichUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.observers.DisposableObserver;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.tatarka.bindingcollectionadapter2.BR;
import me.tatarka.bindingcollectionadapter2.ItemBinding;

public class TabOneVM extends BaseViewModel<Repository> {

    public ObservableList<TabOneItemVM> observableList = new ObservableArrayList<>();
    public ItemBinding<TabOneItemVM> itemBinding = ItemBinding.of(BR.viewModel, R.layout.tab_one_item);


    public ObservableList<PLItemVM> observableListPL = new ObservableArrayList<>();
    public ItemBinding<PLItemVM> itemBindingPL = ItemBinding.of(BR.viewModel, R.layout.item_pl);

    public ObservableList<FJItemVM> observableListFJ = new ObservableArrayList<>();
    public ItemBinding<FJItemVM> itemBindingFJ = ItemBinding.of(BR.viewModel, R.layout.item_nj);


    public ObservableInt showPf = new ObservableInt(View.GONE);
    public ObservableField<String> pfId = new ObservableField<>();
    public ObservableField<String> pfTitle = new ObservableField<>();
    public ObservableField<String> pfTime = new ObservableField<>();
    public ObservableField<String> pfContent = new ObservableField<>();

    private List<TabOneEntity> list = new ArrayList<>();

    public TabOneVM(@NonNull Application application, Repository model) {
        super(application, model);
        getTabData(application);

    }

    @Override
    public void onResume() {
        super.onResume();
        getMyRecord();
        getFjList();
        getPlList();
    }

    private void getMyRecord() {
        Map<String, String> map = new HashMap<>();
        map.put("user_id", UserUtils.getUserAccount());
        model.recent_formula(map)
                .compose(RxUtils.schedulersTransformer())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(this)
                .doOnSubscribe(disposable -> {
                })
                .subscribe(new DisposableObserver<FormulaBean>() {
                    @Override
                    public void onNext(FormulaBean listBean) {
                        if (listBean.issucc) {
                            if (ValidateUtils.isNotEmptyObjectOrString(listBean.getData())) {
                                showPf.set(View.VISIBLE);
                                pfId.set(listBean.getData().getId() + "");
                                pfTitle.set(listBean.getData().getTitle());
                                pfContent.set(listBean.getData().getContent());
                                initWebView(listBean.getData().getContent());
                                pfTime.set(listBean.getData().getAddtime().substring(0, 10));
                            } else {
                                showPf.set(View.GONE);
                            }
                        }else {
                            showPf.set(View.GONE);
                        }

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    public BindingCommand pfClick = new BindingCommand(() -> {
        if (UserUtils.isLogin()){
            Bundle bundle = new Bundle();
            bundle.putString("id", pfId.get());
            bundle.putString("title", pfTitle.get());
            bundle.putString("content", pfContent.get());
            startActivity(AddPfActivity.class, bundle);
        }else {
            startActivity(LoginActivity.class);
        }

    });

    private void getFjList() {
        observableListFJ.clear();
        Map<String, String> map = new HashMap<>();
        map.put("user_id", UserUtils.getUserAccount());
        model.fermentList(map)
                .compose(RxUtils.schedulersTransformer())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(this)
                .doOnSubscribe(disposable -> {
                })
                .subscribe(new DisposableObserver<FaJiaoListBean>() {
                    @Override
                    public void onNext(FaJiaoListBean listBean) {
                        if (listBean.issucc)
                            if (ValidateUtils.isNotEmptyObjectOrString(listBean.getData())) {
                                if (listBean.getData().size() > 0) {
                                    observableListFJ.add(new FJItemVM(TabOneVM.this,
                                            listBean.getData().get(listBean.getData().size()-1)));

                                }
                            }

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void getPlList() {
        observableListPL.clear();
        Map<String, String> map = new HashMap<>();
        map.put("user_id", UserUtils.getUserAccount());
        model.soakgrainList(map)
                .compose(RxUtils.schedulersTransformer())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(this)
                .doOnSubscribe(disposable -> {
                })
                .subscribe(new DisposableObserver<PaoLiangListBean>() {
                    @Override
                    public void onNext(PaoLiangListBean listBean) {
                        if (listBean.issucc)
                            if (ValidateUtils.isNotEmptyObjectOrString(listBean.getData())) {
                                if (listBean.getData().size() > 0) {
                                    observableListPL.add(new PLItemVM(TabOneVM.this,
                                            listBean.getData().get(listBean.getData().size()-1)));
                                }
                            }

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void getTabData(Application application) {
        for (int i = 0; i < 10; i++) {
            TabOneEntity tabOneEntity = new TabOneEntity();
            tabOneEntity.ImgRes = application.getResources().getIdentifier("h_" + (i), "mipmap", getPackageName());
            tabOneEntity.tabStr = application.getResources().getStringArray(R.array.tab_str)[i];
            list.add(tabOneEntity);
        }


        for (TabOneEntity entity : list) {
            TabOneItemVM tabOneItemVM = new TabOneItemVM(this, entity);
            observableList.add(tabOneItemVM);
        }

    }


    public BindingCommand addPf = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            if (UserUtils.isLogin()){
                startActivity(AddPfActivity.class);
            }else {
                startActivity(LoginActivity.class);
            }
        }
    });

    public BindingCommand lookPf = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            if (UserUtils.isLogin()){
                startActivity(PfRecordActivity.class);
            }else {
                startActivity(LoginActivity.class);
            }
        }
    });

    public BindingCommand lookPl = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            if (UserUtils.isLogin()){
                Bundle bundle = new Bundle();
                bundle.putString("flag", "pl");
                startActivity(DetailRecordActivity.class, bundle);
            }else {
                startActivity(LoginActivity.class);
            }

        }
    });


    public BindingCommand lookNj = new BindingCommand(() -> {
        if (UserUtils.isLogin()){
            Bundle bundle = new Bundle();
            bundle.putString("flag", "nj");
            startActivity(DetailRecordActivity.class, bundle);
        }else {
            startActivity(LoginActivity.class);
        }
    });


    public BindingCommand addRecord = new BindingCommand(() -> {
        if (UserUtils.isLogin()) {
            startActivity(AddRecordActivity.class);
        } else {
            startActivity(LoginActivity.class);
        }
    });

    public BindingCommand khRecord = new BindingCommand(() -> {
        if (UserUtils.isLogin()) {
            startActivity(KhRecordActivity.class);
        } else {
            startActivity(LoginActivity.class);
        }
    });

    public BindingCommand xlRecord = new BindingCommand(() -> {
        if (UserUtils.isLogin()) {
            startActivity(SaveXlActivity.class);
        } else {
            startActivity(LoginActivity.class);
        }
    });

    WebView mTextView;

    public void setView(WebView tvContent) {
        mTextView = tvContent;
    }

    public void initWebView(String data) {

        WebSettings settings = mTextView.getSettings();

        //settings.setUseWideViewPort(true);//调整到适合webview的大小，不过尽量不要用，有些手机有问题
        settings.setLoadWithOverviewMode(true);//设置WebView是否使用预览模式加载界面。
        settings.setAllowUniversalAccessFromFileURLs(true);
        settings.setAllowFileAccess(true);
        settings.setAllowFileAccessFromFileURLs(true);


        mTextView.setVerticalScrollBarEnabled(false);//不能垂直滑动
        mTextView.setHorizontalScrollBarEnabled(false);//不能水平滑动
        settings.setTextSize(WebSettings.TextSize.NORMAL);//通过设置WebSettings，改变HTML中文字的大小
        settings.setJavaScriptCanOpenWindowsAutomatically(true);//支持通过JS打开新窗口
        //设置WebView属性，能够执行Javascript脚本
        mTextView.getSettings().setJavaScriptEnabled(true);//设置js可用

        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);//支持内容重新布局
        mTextView.setWebViewClient(webViewClient);
        mTextView.setWebChromeClient(new WebChromeClient());
        data = "</Div><head><style>body{font-size:16px}</style>" +
                "<style>img{ width:100% !important;margin-top:0.4em;margin-bottom:0.4em}</style>" +
                "<style>ul{ padding-left: 1em;margin-top:0em}</style>" +
                "<style>ol{ padding-left: 1.2em;margin-top:0em}</style>" +
                "</head>" + data;

        ArrayList<String> arrayList = RichUtils.returnImageUrlsFromHtml(data);
        if (arrayList.size() > 0) {
            for (int i = 0; i < arrayList.size(); i++) {
                if (!arrayList.get(i).contains("http")) {
                    //如果不是http,那么就是本地绝对路径，要加上file
                    data = data.replace(arrayList.get(i), arrayList.get(i));
                }
            }
        }

        mTextView.loadDataWithBaseURL(null, data, "text/html", "utf-8", null);
    }

    public WebViewClient webViewClient = new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
        }


        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.proceed();
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return super.shouldOverrideUrlLoading(view, url);
        }


        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            String url = request.getUrl().toString();
            return super.shouldOverrideUrlLoading(view, request);
        }


    };

}
